package cn.unknowpupil.service.system.impl;

import cn.unknowpupil.common.core.constant.SecurityConstants;
import cn.unknowpupil.common.core.resopnse.ResultResponse;
import cn.unknowpupil.common.core.utils.StringUtils;
import cn.unknowpupil.common.redis.utils.RedisUtil;
import cn.unknowpupil.common.security.dto.LoginUser;
import cn.unknowpupil.common.security.properties.SecurityProperties;
import cn.unknowpupil.common.security.utils.SecurityUtils;
import cn.unknowpupil.domain.dto.login.SysUserOnline;
import cn.unknowpupil.domain.system.SysUser;
import cn.unknowpupil.service.system.ISysUserService;
import cn.unknowpupil.service.system.IUserOnlineService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Created at 2020/10/23 by w10g <br>
 * Initialize UserOnlineServiceImpl ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Service
public class UserOnlineServiceImpl implements IUserOnlineService {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SecurityProperties securityProperties;


    @Override
    public IPage<SysUserOnline> getOnline(String userName, String ipAdders) {
        Set<String> keys = redisUtil.keys(securityProperties.getOnlineKey() + "*");
        List<SysUserOnline> userOnlineList = Lists.newArrayList();
        keys.forEach(o -> {
            LoginUser user = redisUtil.getCacheObject(o);
            if (StringUtils.isNotBlank(ipAdders) && StringUtils.isNotBlank(userName)) {
                if (StringUtils.equals(ipAdders, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(this.selectOnlineByInfo(ipAdders, userName, user));
                }
            } else if (StringUtils.isNotEmpty(ipAdders)) {
                if (StringUtils.equals(ipAdders, user.getIpaddr())) {
                    userOnlineList.add(this.selectOnlineByIpAdders(ipAdders, user));
                }
            } else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user)) {
                if (StringUtils.equals(userName, user.getUsername())) {
                    userOnlineList.add(this.selectOnlineByUserName(userName, user));
                }
            } else {
                userOnlineList.add(this.loginUserToUserOnline(user));
            }
        });
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTableWithPage(userOnlineList);
    }

    @Override
    public long clean() {
        Set<String> keys = redisUtil.keys(securityProperties.getOnlineKey() + "*");
        List<String> userOnlineList = Lists.newArrayList();
        keys.forEach(o -> {
                    LoginUser user = redisUtil.getCacheObject(o);
                    if(user.isMultilateralLogin()){
                        userOnlineList.add(securityProperties.getOnlineKey()+user.getToken());
                    }
        });
        return redisUtil.dels(userOnlineList);
    }


    /**
     * 通过登录地址/用户名称查询信息
     *
     * @param ipAdders 登录地址
     * @param userName 用户名称
     * @param user     用户信息
     * @return 在线用户信息
     */
    public SysUserOnline selectOnlineByInfo(String ipAdders, String userName, LoginUser user) {
        if (StringUtils.equals(ipAdders, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
            return loginUserToUserOnline(user);
        }
        return null;
    }

    /**
     * 通过登录地址查询信息
     *
     * @param ipAdders 登录地址
     * @param user     用户信息
     * @return 在线用户信息
     */
    public SysUserOnline selectOnlineByIpAdders(String ipAdders, LoginUser user) {
        if (StringUtils.equals(ipAdders, user.getIpaddr())) {
            return loginUserToUserOnline(user);
        }
        return null;
    }

    /**
     * 通过用户名称查询信息
     *
     * @param userName 用户名称
     * @param user     用户信息
     * @return 在线用户信息
     */
    public SysUserOnline selectOnlineByUserName(String userName, LoginUser user) {
        if (StringUtils.equals(userName, user.getUsername())) {
            return loginUserToUserOnline(user);
        }
        return null;
    }


    private SysUserOnline loginUserToUserOnline(LoginUser user) {
        SysUserOnline sysUserOnline = new SysUserOnline();
        sysUserOnline.setTokenId(user.getToken());
        sysUserOnline.setUserName(user.getUsername());
        sysUserOnline.setIpaddr(user.getIpaddr());
        sysUserOnline.setLoginLocation(user.getLoginLocation());
        sysUserOnline.setBrowser(user.getBrowser());
        sysUserOnline.setOs(user.getOs());
        sysUserOnline.setMultilateralLogin(user.isMultilateralLogin());
        sysUserOnline.setLoginTime(user.getLoginTime());
        return sysUserOnline;

    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    private IPage<SysUserOnline> getDataTableWithPage(List<SysUserOnline> userOnlineList) {
        IPage<SysUserOnline> page = new Page<>();
        page.setPages(1);
        page.setRecords(userOnlineList);
        page.setTotal(userOnlineList.size());
        page.setSize(userOnlineList.size());
        page.setCurrent(1);
        return page;

    }
}
